<!DOCTYPE HTML>
<html>

<head>
   <meta charset="utf-8">
   <title>webSocket智能客服系统</title>
   <link rel="stylesheet" href="/css/bootstrap.min.css">
   <style>
      html,body{
         height: 100%;
      }
      body {
         background: url('/images/bg-01.jpg');
         background-size: cover;
      }

      .container{
         width: 750px;
         height: 100%;
         display: flex;
         justify-content: center;
         align-items: center;
      }
      .well {
         flex:1;
         background: rgba(245, 245, 245, .8);
      }

      #chat-content {
         height: 240px;
         overflow-y: auto;
      }
   </style>
</head>

<body>

   <div class="container">
      <!-- 聊天内容展示区域 -->
      <div class="well">
         <div class="clearfix">
            <h4><%=title%>
               <span onclick="clearChatLog()" class="btn btn-danger btn-xs pull-right">清空</span>
            </h4>
         </div>
         <hr>
         <div id="chat-content" class="clearfix">

         </div>

         <hr>

         <div>
            <div class="form-group">
               <input type="text" id="msg" class="form-control" placeholder="请输入聊天内容" autofocus
                  onkeyup="keyupHandle(event)" />
            </div>
            <div class="form-group clearfix">
               <button class="btn btn-success" onclick="sendMsg()">发送消息</button>
            </div>
         </div>

      </div>

   </div>

</body>
<script src="/js/jquery.min.js"></script>
<script src="/js/socket.io.js"></script>
<script type="text/javascript">
   var socket = io('http://localhost/');
   // 创建链接  
   socket.on('connect', function () {
      //  发送消息给服务端
      // socket.send({name:'zs',age:30});
      //  通过监听自定义事件, 接收服务端的消息
      socket.on('content', function ({ msg }) {
         var html = `<div class="alert alert-success"><strong>智能客服:&nbsp;</strong>${msg}</div>`
         $("#chat-content").append(html);
         // 滚动页面
         autoScroll();
      });
   });

   function sendMsg() {
      let msg = $("#msg").val().trim();
      if (msg == '') {
         return alert('消息内容不能为空');
      }
      var html = `<div class="alert alert-warning"><strong>我:&nbsp;</strong>${msg}</div>`
      $("#chat-content").append(html);
      socket.send(msg);
      // 清空输入框
      $('#msg').val('');
      // 滚动页面
      autoScroll();
   }


   // 回车键发送消息
   function keyupHandle(event) {
      if (event.keyCode == 13) {
         sendMsg();
      }
   }

   // 自动滚动页面
   function autoScroll() {
      var chat = $("#chat-content");
      chat.animate({ scrollTop: chat.prop('scrollHeight') - chat.height() }, 100)
   }
   // 清空聊天记录
   function clearChatLog() {
      $('#chat-content').empty();
   }
</script>

</html>